<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { FullScreen, House, Calendar, Document, Setting, User, OfficeBuilding, List, Fold, Expand } from '@element-plus/icons-vue'
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'

const router = useRouter()
const user = ref(JSON.parse(localStorage.getItem('user')) || null)
const isFullscreen = ref(false)
const isCollapse = ref(false)

const isLoggedIn = computed(() => !!user.value)
const isAdmin = computed(() => user.value && user.value.role === 'ADMIN')

// 监听 localStorage 中的用户信息变化
const updateUserFromStorage = () => {
  try {
    const userStr = localStorage.getItem('user')
    user.value = userStr ? JSON.parse(userStr) : null
    console.log('用户状态更新:', user.value ? user.value.username : '未登录')
  } catch (e) {
    console.error('解析用户信息失败:', e)
    user.value = null
  }
}

// 添加 storage 事件监听器
onMounted(() => {
  window.addEventListener('storage', (e) => {
    if (e.key === 'user') {
      updateUserFromStorage()
    }
  })
  
  // 自定义事件监听器
  window.addEventListener('user-login', updateUserFromStorage)
  window.addEventListener('user-logout', updateUserFromStorage)
})

const logout = () => {
  localStorage.removeItem('user')
  user.value = null
  // 触发自定义事件
  window.dispatchEvent(new Event('user-logout'))
  router.push('/login')
}

const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen().then(() => {
      isFullscreen.value = true
      document.documentElement.classList.add('fullscreen-enabled')
    }).catch(err => {
      console.error(`无法进入全屏模式: ${err.message}`);
    })
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen().then(() => {
        isFullscreen.value = false
        document.documentElement.classList.remove('fullscreen-enabled')
      }).catch(err => {
        console.error(`无法退出全屏模式: ${err.message}`);
      })
    }
  }
}

const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}
</script>

<template>
  <div class="app-container">
    <!-- 登录/注册页面使用不同布局 -->
    <template v-if="$route.path === '/login' || $route.path === '/register'">
      <div class="auth-layout">
        <router-view />
      </div>
    </template>
    
    <!-- 后台管理系统布局 -->
    <template v-else>
      <el-container class="admin-layout">
        <el-aside v-if="isLoggedIn" width="auto" class="sidebar">
          <div class="logo-container">
            <h2 class="logo">会议室系统</h2>
          </div>
          
          <el-menu
            :default-active="$route.path"
            :collapse="isCollapse"
            :router="true"
            class="sidebar-menu"
            background-color="#2b3a42"
            text-color="#fff"
            active-text-color="#409EFF"
          >
            <el-menu-item index="/">
              <el-icon><House /></el-icon>
              <template #title>首页</template>
            </el-menu-item>
            
            <el-menu-item index="/new-reservation" @click="isLoggedIn ? router.push('/new-reservation') : router.push('/login')">
              <el-icon><Calendar /></el-icon>
              <template #title>预约会议室</template>
            </el-menu-item>
            
            <el-menu-item index="/my-reservations" @click="isLoggedIn ? router.push('/my-reservations') : router.push('/login')">
              <el-icon><Document /></el-icon>
              <template #title>我的预约</template>
            </el-menu-item>
            
            <template v-if="isAdmin">
              <el-sub-menu index="/admin">
                <template #title>
                  <el-icon><Setting /></el-icon>
                  <span>系统管理</span>
                </template>
                
                <el-menu-item index="/users">
                  <el-icon><User /></el-icon>
                  <template #title>用户管理</template>
                </el-menu-item>
                
                <el-menu-item index="/rooms">
                  <el-icon><OfficeBuilding /></el-icon>
                  <template #title>会议室管理</template>
                </el-menu-item>
                
                <el-menu-item index="/reservations" @click="router.push('/reservations')">
                  <el-icon><List /></el-icon>
                  <template #title>预约管理</template>
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-menu>
        </el-aside>
        
        <el-container>
          <el-header height="60px" class="admin-header">
            <div class="header-left">
              <el-icon class="collapse-btn" @click="toggleSidebar">
                <Fold v-if="!isCollapse" />
                <Expand v-else />
              </el-icon>
            </div>
            
            <div class="header-right">
              <el-tooltip content="全屏显示" placement="bottom" v-if="isLoggedIn">
                <el-button @click="toggleFullscreen" circle>
                  <el-icon><FullScreen /></el-icon>
                </el-button>
              </el-tooltip>
              
              <template v-if="isLoggedIn">
                <el-dropdown trigger="click">
                  <div class="user-info">
                    <el-avatar :size="32" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                    <span>{{ user.name || user.username }}</span>
                  </div>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
              
              <template v-else>
                <router-link to="/login">
                  <el-button type="primary">登录</el-button>
                </router-link>
                <router-link to="/register" class="ml-2">
                  <el-button>注册</el-button>
                </router-link>
              </template>
            </div>
          </el-header>
          
          <el-main>
            <router-view />
          </el-main>
          
          <el-footer height="40px">
            <div class="footer-content">
              &copy; {{ new Date().getFullYear() }} 会议室租借系统
            </div>
          </el-footer>
        </el-container>
      </el-container>
    </template>
  </div>
</template>

<style>
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  overflow: hidden;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.fullscreen-enabled {
  overflow: hidden;
}

.app-container {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}

/* 登录/注册页面布局 */
.auth-layout {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

/* 后台管理系统布局 */
.admin-layout {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  background-color: #2b3a42;
  transition: width 0.3s;
  overflow: hidden;
  height: 100%;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  color: white;
  background-color: #2b3a42;
}

.logo {
  color: white;
  margin: 0;
  font-size: 18px;
  white-space: nowrap;
  overflow: hidden;
}

.sidebar-menu {
  border-right: none;
  height: calc(100% - 60px);
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 200px;
}

/* 头部样式 */
.admin-header {
  background-color: #fff;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.collapse-btn {
  font-size: 20px;
  cursor: pointer;
  margin-right: 20px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.user-info span {
  margin-left: 8px;
}

/* 主内容区域样式 */
.el-main {
  background-color: #f5f7fa;
  padding: 0;
  height: calc(100vh - 100px);
  overflow-y: auto;
}

/* 页脚样式 */
.el-footer {
  background-color: #fff;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
}

.footer-content {
  text-align: center;
  color: #606266;
  font-size: 12px;
}

.ml-2 {
  margin-left: 8px;
}
</style>
